import axios from 'axios'
import NProgress from 'nprogress'
import { ElMessage } from 'element-plus'
import { defaultRequestInterceptors, defaultResponseInterceptors,defaultErrorInterceptors } from './config'
import { REQUEST_TIMEOUT } from '@/constants'

export const PATH_URL = import.meta.env.VITE_APP_BASE_URL

const abortControllerMap = new Map()

const axiosInstance = axios.create({
  baseURL: PATH_URL,
  timeout: REQUEST_TIMEOUT
})

// 请求拦截器：添加 abort 控制器
axiosInstance.interceptors.request.use((config) => {
  // console.log('🚀 请求地址:', config.baseURL + config.url)
  const controller = new AbortController()
  const url = config.url || ''
  config.signal = controller.signal
  abortControllerMap.set(url, controller)
  NProgress.start()
  return config
})

// 响应拦截器：移除 abort 控制器
axiosInstance.interceptors.response.use(
  (response) => {
    const url = response.config.url || ''
    abortControllerMap.delete(url)
    NProgress.done()
    return response
  },
  (error) => {
    const url = error?.config?.url || ''
    abortControllerMap.delete(url)
    NProgress.done()
    // ElMessage.error(error.message || '请求错误')
    return Promise.reject(error)
  }
)

// 安装默认拦截器
// 加载默认拦截器（成功 + 错误）
axiosInstance.interceptors.request.use(defaultRequestInterceptors)
axiosInstance.interceptors.response.use(
  defaultResponseInterceptors,
  defaultErrorInterceptors
)

const service = {
  request(config) {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptors) {
        config = config.interceptors.requestInterceptors(config)
      }

      axiosInstance
        .request(config)
        .then(resolve)
        .catch(reject)
    })
  },

  cancelRequest(url) {
    const urlList = Array.isArray(url) ? url : [url]
    for (const u of urlList) {
      abortControllerMap.get(u)?.abort()
      abortControllerMap.delete(u)
    }
  },

  cancelAllRequest() {
    abortControllerMap.forEach((controller) => controller.abort())
    abortControllerMap.clear()
  }
}

export default service
